package com.syqc.videos

import android.Manifest
import android.os.Build
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.permissionx.guolindev.PermissionX
import com.syqc.comlib.base.BaseBarActivity
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.startActivityTo
import com.syqc.utils.Keys
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.utils.GsonUtil
import com.syqc.comlib.utils.loadGif
import com.syqc.comlib.utils.toast
import com.syqc.entity.HistoryVideo
import com.syqc.entity.KeyValue
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityVideoInfoBinding
import com.syqc.monitor.popup.DownLoadDialog
import com.syqc.monitor.popup.VideoTimeDialog
import com.syqc.monitor.ui.newaddcar.KeyValuePopup
import com.syqc.utils.TimeUtil


/**
 *@Author Jasper
 *@Time   2020/9/29
 *@Desc   历史视频列表
 */
class HistoryVideoInfoActivity :
    BaseBarActivity<ActivityVideoInfoBinding>(ActivityVideoInfoBinding::inflate) {

    private var isTmn = true
    private var carId = ""
    private var title = ""
    private val mAdapter by lazy { HistoryVideoInfoAdapter(isTmn) }
    private val mVM by viewModels<HistoryVideoViewModel>()

    private val mKeyValuePopup: KeyValuePopup by lazy {
        KeyValuePopup(this)
    }

    private var passList: ArrayList<KeyValue>? = null

    //空布局
    private val emptyView by lazy {
        val view = layoutInflater.inflate(
            R.layout.layout_empty_view,
            binding.rvVideoInfo,
            false
        )
        view.findViewById<ImageView>(R.id.ivNoData).loadGif(this, R.mipmap.ic_empty)
        view
    }

    private val mDownDialog by lazy {
        DownLoadDialog(this, onCancel = this::onClick, onPlay = this::onPlayVideo)
    }

    private val mDialog by lazy {
        VideoTimeDialog(this) { start, end, sdate, edate, videoType ,isChange->
            if (!isFinishing) mDownDialog.show()
            mDownDialog.setDownInfo(mVM.history!!,sdate, edate, videoType,isChange)
            mVM.uploadFtp(start, end, videoType,isChange)
        }
    }

    override fun initView() {
        isTmn = intent.getBooleanExtra("isTmn", true)
        carId = intent.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
        title = intent.getStringExtra(Keys.INTENT_TITLE) ?: ""
        val passJson = intent.getStringExtra("passJson")
        if (!passJson.isNullOrEmpty()) {
            val keyValues = GsonUtil.formArrayList(passJson, KeyValue::class.java)
            passList = ArrayList(keyValues)
            binding.lrTvPass.isVisible = true
        } else {
            binding.lrTvPass.isVisible = false
        }


        ToolbarHelper.setToolbar(this, title)
        binding.rvVideoInfo.layoutManager = LinearLayoutManager(this)
        binding.rvVideoInfo.adapter = mAdapter

        LiveDataBus.get().with("key_history_video")
            .observeStick(this) {
                val result = it as MutableList<HistoryVideo.Result>
                result.forEach { item ->
                    item.duration = TimeUtil.instance.getDiffAllTime(
                        "20${item.startTime}",
                        "20${item.endTime}"
                    )
                }
                mVM.setResult(result)
            }

        mVM.resultLive.observe(this) {
            if (it.isNullOrEmpty()) {
                mAdapter.setEmptyView(emptyView)
            }
            mAdapter.setNewInstance(it)
        }

        mVM.uploadLive.observe(this) {
            when (it) {
                DownState.UpQuery -> {
                    mDownDialog.setPlayVideo(false)
                    mDownDialog.setProgress(true)
                    mDownDialog.setMessage(R.string.desc_video_type_query)
                    mDownDialog.setDownTitle(R.string.desc_video_cancel_query)
                }

                DownState.Upload -> {
                    mDownDialog.setMessage(R.string.desc_video_type_start_up)
                    mDownDialog.setDownTitle(R.string.desc_video_type_cancel_upload)
                }

                DownState.UploadFail -> {
                    mDownDialog.setVisible(false)
                    mDownDialog.setMessage(mVM.getUpState())
                    mDownDialog.setDownTitle(R.string.desc_cancel)
                }

                DownState.UpProgressSuccess -> {
                    mDownDialog.setVisible(false)
                    mDownDialog.setMessage(R.string.desc_video_type_up_success)
                }

                DownState.UpProgress -> {
                    mDownDialog.setVisible(true)
                    mDownDialog.setMessage(mVM.getUpState())
                    mDownDialog.setJdSize(mVM.jd,mVM.upSize)
                    mDownDialog.setDownTitle(R.string.desc_video_type_cancel_upload)
                }

                DownState.UpProgressFail -> {
                    mDownDialog.setMessage(mVM.getUpState())
                    mDownDialog.setDownTitle(R.string.desc_cancel)
                }

                DownState.UpCancel -> {
                    mDownDialog.setMessage(R.string.desc_video_type_cancel_up)
                }

                DownState.UpCancelFail -> {
                    mDownDialog.setMessage(mVM.getUpState())
                }

                DownState.DownStart -> {
                    mDownDialog.setMessage(R.string.desc_video_type_start_down)
                    mDownDialog.setDownTitle(R.string.desc_cancel_down)
                }

                DownState.DownProgress -> {
                    mDownDialog.setMessage(getString(R.string.desc_video_type_down_progress))
                }

                DownState.DownSuccess -> {
                    mDownDialog.setProgress(false)
                    mDownDialog.setMessage(R.string.desc_video_type_down_success)
                    mDownDialog.setDownTitle(R.string.hint_close)
                    mDownDialog.setPlayVideo(true)
                }

                DownState.DownFail -> {
                    mDownDialog.setMessage(R.string.desc_video_type_down_fail)
                    mDownDialog.setDownTitle(R.string.hint_close)
                }

                else -> {
                    mDownDialog.dismiss()
                }
            }
        }

    }


    private fun toPlayer(
        isTmn: Boolean, carId: String?,
        title: String, item: HistoryVideo.Result
    ) {
        if (isTmn) {
            startActivityTo<TmnPlayerActivity>(this@HistoryVideoInfoActivity) {
                putExtra(Keys.INTENT_CAR_ID, carId)
                putExtra(Keys.INTENT_TITLE, title)
                putExtra(Keys.INTENT_DATA, item)
            }
        } else {
            startActivityTo<PlatPlayerActivity>(this@HistoryVideoInfoActivity) {
                val channelName = if (item.channelName.isNullOrEmpty()) {
                    getString(R.string.desc_video_pass) + item.channel
                } else {
                    item.channelName
                }
                putExtra(Keys.INTENT_CAR_ID, carId)
                putExtra(Keys.INTENT_TITLE, "$title  $channelName")
                putExtra(Keys.INTENT_DATA, item.fileName)
                putExtra(Keys.INTENT_OTHER, item.duration)
            }
        }
    }

    override fun setListener() {
        binding.lrTvPass.rightClick {
            mKeyValuePopup.showPopupWindow(
                window.decorView,
                getString(R.string.desc_video_passes),
                passList!!,
                mVM.tmnPass
            )
        }

        mKeyValuePopup.setCallBack(object : KeyValuePopup.CallBack {
            override fun onBack(entity: KeyValue, index: Int) {
                mVM.tmnPass = entity.key.toInt()
                mVM.search(entity.key.toInt())
                binding.lrTvPass.setRightText(entity.value)
            }

        })


        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (carId.isEmpty()) return@setOnItemChildClickListener
            val item = mAdapter.data[position]
            mVM.history = item
            mVM.carId = carId
            when (view.id) {
                R.id.iv_video_download -> {
                    getPremiss()
                }

                R.id.iv_video_history -> {

                    toPlayer(isTmn, carId, title, item)
                }
            }
        }
    }


    private fun onClick() {
        when (mVM.getDownState()) {
            DownState.UpProgress -> {
                mVM.uploadControl()
                mDownDialog.dismiss()
            }

            else -> {
                mDownDialog.dismiss()
            }
        }
    }

    /**
     * 播放视频
     *
     */
    private fun onPlayVideo() {

        val url = mVM.getPlayPath()
        val fileName = url.split("/").last()
        startActivityTo<PlayDownActivity>(this) {
            putExtra(Keys.INTENT_TITLE, fileName)
            putExtra(Keys.INTENT_DATA, url)
        }
    }

    //下载文件读写权限
    private fun getPremiss() {
        val requestList = ArrayList<String>()
        requestList.add(Manifest.permission.CAMERA)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestList.add(Manifest.permission.READ_MEDIA_IMAGES)
            requestList.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            requestList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        PermissionX.init(this@HistoryVideoInfoActivity).permissions(requestList)
            .explainReasonBeforeRequest()
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(
                    deniedList,
                    getString(
                        R.string.desc_permissions_msg,
                        getString(R.string.app_name)
                    ),
                    getString(R.string.desc_com_sure),
                    getString(R.string.desc_cancel)
                )
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    mDialog.show()
                    mDialog.setTime("20${mVM.history!!.startTime}", "20${mVM.history!!.endTime}")
                } else {
                    toast(R.string.toast_no_has_permission)
                }
            }
    }
}